package com.zjdiepu.www.manage.api.system;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import net.sf.jxls.exception.ParsePropertyException;
import net.sf.jxls.transformer.XLSTransformer;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.zjdiepu.www.base.BaseController;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.PageExt;
import com.zjdiepu.www.base.core.PageVo;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.common.util.DateUtil;
import com.zjdiepu.www.ibiz.base.IBaseRealTimeCustomerService;
import com.zjdiepu.www.model.base.dto.SysUser;
import com.zjdiepu.www.model.yw.dto.YwBusiness;

/**
 * 实时报表Controller层<br/>
 * @author xiongxiaotun<br/>
 * @time 2017年04月24日 14时34分<br/>
 * @since 1.0<br/>
 */
@RestController
@RequestMapping(value= "BaseRealTimeCustomerController", produces="application/json;charset=UTF-8")
@Api(tags = {"实时报表"}, produces="application/json;charset=UTF-8")
public class BaseRealTimeCustomerController extends BaseController {
	private Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private IBaseRealTimeCustomerService baseRealTimeCustomerService;
    /**
     * @author xiongxiaotun <br/>
     * @Title: htyjyhList  <br/>
     * @Description: 实时报表:合同移交银行 <br/>
     * @param ywBusinessQueryRequest
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "实时报表:合同移交银行",response = YwBusiness.class, httpMethod="POST", tags={"客户列表"})
    @RequestMapping(value = "htyjyhList", method = RequestMethod.POST)
    public ApiResponse htyjyhList(@Validated @ModelAttribute PageExt pageExt, 
    		Date time_send_to_bankStart, Date time_send_to_bankEnd, 
    		String customer_no, String customer_name, String salesman_name, String chinese_time){
    	SysUser currentUser = (SysUser)getCurrentUser();
    	Integer rows = pageExt.getRows();
    	Integer page = pageExt.getPage();
    	Integer offset = pageExt.getOffset();
    	
		Map<String, Object> paramMap = CollectionInitUtil.emptyMap();
		paramMap.put("codeUnits", currentUser.getCodeUnits());
		paramMap.put("bankLoan", currentUser.getLoanBank());
		
		paramMap.put("chinese_time", chinese_time);
		paramMap.put("customer_no", customer_no);
		paramMap.put("customer_name", customer_name);
		paramMap.put("salesman_name", salesman_name);
		paramMap.put("time_send_to_bankStart", time_send_to_bankStart);
		paramMap.put("time_send_to_bankEnd", DateUtil.increaseDate(time_send_to_bankEnd, 1));
		
		PageVo pageVo = new PageVo();
		pageVo.setPageSize(rows);
		pageVo.setPage(page);
        int records = baseRealTimeCustomerService.countHtyjyh(paramMap);
        pageVo.setRecords(records);
        if (records > 0) {
        	paramMap.put("orderSql", pageExt.getOrderSql());
        	paramMap.put("offset", offset);
        	paramMap.put("rows", rows);
            List<Map<String, Object>> datas = baseRealTimeCustomerService.selectHtyjyh(paramMap);
            pageVo.setRows(datas);
        } else {
            pageVo.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(pageVo);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: exportHtyjyhList  <br/>
     * @Description: 查询合同移交银行列表 <br/>
     * @param pageExt
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "导出合同移交银行列表",response = YwBusiness.class, httpMethod="POST")
    @RequestMapping(value = "exportHtyjyhList", method = {RequestMethod.POST, RequestMethod.GET})
    public ApiResponse exportHtyjyhList(@Validated @ModelAttribute PageExt pageExt, 
    		Date time_send_to_bankStart, Date time_send_to_bankEnd, 
    		String customer_no, String customer_name, String salesman_name, String chinese_time, HttpServletResponse response){
    	SysUser currentUser = (SysUser)getCurrentUser();
    	
		Map<String, Object> paramMap = CollectionInitUtil.emptyMap();
		paramMap.put("codeUnits", currentUser.getCodeUnits());
		paramMap.put("bankLoan", currentUser.getLoanBank());
		paramMap.put("chinese_time", chinese_time);
		paramMap.put("customer_no", customer_no);
		paramMap.put("customer_name", customer_name);
		paramMap.put("salesman_name", salesman_name);
		paramMap.put("time_send_to_bankStart", time_send_to_bankStart);
		paramMap.put("time_send_to_bankEnd", DateUtil.increaseDate(time_send_to_bankEnd, 1));
		
        /**
         * 检查是否有记录
         */
        String method = request.getMethod();
    	if(RequestMethod.POST.name().equals(method)) {
    		int records = baseRealTimeCustomerService.countHtyjyh(paramMap);
    		if(records > 0) {
    			return ApiResponse.success(true);
    		} else {
    			return ApiResponse.fail("999", "没有数据可以导出");
    		}
    	}
    	
    	paramMap.put("orderSql", pageExt.getOrderSql());
        List<Map<String, Object>> datas = baseRealTimeCustomerService.selectHtyjyh(paramMap);
        for(Map<String, Object> data : datas) {
        	Date time_send_to_bank = (Date)data.get("time_send_to_bank");
        	data.put("time_send_to_bank", DateUtil.dateTo8String(time_send_to_bank));
        }
        String templet = request.getSession(true).getServletContext().getRealPath("/WEB-INF/templet/he_tong_yi_jiao_yin_hang.xls");
		try (FileInputStream is = new FileInputStream(templet); ){
			XLSTransformer transformer = new XLSTransformer();  
			//展示数据
	    	Map<String, Object> responseData = CollectionInitUtil.emptyMap();
	    	responseData.put("datas", datas);
			Workbook workbook = transformer.transformXLS(is, responseData);
			String fileName = "合同移交银行列表";
			response.reset();
			response.addHeader("Content-Disposition",
					"attachment;filename=" + new String(fileName.getBytes(isIE(request)?"GBK":"UTF-8"), "ISO-8859-1") +".xls");
			response.setContentType("application/vnd.ms-excel;charset=UTF-8");
			OutputStream outPutStream = response.getOutputStream();
			workbook.write(outPutStream);  
		} catch (ParsePropertyException | InvalidFormatException | IOException e) {
			logger.error("导出合同移交银行列表异常.异常栈:{}", e);
		}
		return null;
    }
}
